package hot100.双指针.矩阵;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/** 54-螺旋矩阵
/**
 * 示例 matrix = [[1,2,3],
 *               [4,5,6],
 *               [7,8,9]]
 * 输出 [1,2,3,6,9,8,7,4,5]
 */
public class matrixArrayToOneArray54 {

    public List<Integer> method(int[][] matrix) {
        /*List<Integer> result = new ArrayList<Integer>();
        int nowCount = 0,
                t = 0,l = 0,
                b = matrixArray.length -1,r = matrixArray[0].length -1;
                //int b = matrixArray.length -1; int r = matrixArray[0].length -1;
        while (true) {
            for (int i=l;i<=r;i++) result.add(matrixArray[t][i]);
            if (++t == b) break;
            for (int i=t;i<=b;i++) result.add(matrixArray[i][r]);
            if (--r == l) break;
            for (int i=r;i>=l;i--) result.add(matrixArray[b][i]);
            if (--b == t) break;
            for (int i=b;i>=t;i--) result.add(matrixArray[i][l]);
            if (++l == r) break;
        }

        return result;*/

        if (matrix.length == 0)
            return new ArrayList<Integer>();
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
        Integer[] res = new Integer[(r + 1) * (b + 1)];
        /** a左到右 b上到下 c右到左 d下到上
         * 1 为什么只有ad需要判断? 因为循环的边界只分为 奇数结尾和偶数结尾 ? a专属于奇数结尾 : b专属于偶数结尾
         * 2 关于边界重合问题  也即满足第一点填充即可 -> ++X和X++ 后者才表示当前的 前者实际上是提前了一行
         * **/
        while (true) {
            for (int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right
            if (t++ == b) break; // or if (++t > b) break;
            for (int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom
            --r; //if (l > --r) break;
            for (int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left
            --b; //if (t > --b) break;
            for (int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top
            if (++l > r) break;
        }
        return Arrays.asList(res);

    }

    public static void main(String[] args) {
        matrixArrayToOneArray54 m = new matrixArrayToOneArray54();
        System.out.println(
                m.method(
                        //new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
                        //new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}
                        new int[][]{
                                {1, 2, 3, 4},
                                {5, 6, 7, 8},
                                {9, 10, 11, 12},
                                {13, 14, 15, 16}}
                        )
                );
    }
}